using System;
using System.Windows.Media.Media3D;
using System.Windows;

namespace C4F.VistaP2P.WPF
{
    public class Plane
    {
        public Plane()
        {
            upperLeft = new Point3D(0, 0, 0);
            lowerRight = new Point3D(1, 1, 0);
            planeChanged = true;
        }

        public Point3D UpperLeft
        {
            set
            {
                if (value != upperLeft)
                {
                    upperLeft = value;
                    planeChanged = true;
                }
            }
        }

        public Point3D LowerRight
        {
            set
            {
                if (value != lowerRight)
                {
                    lowerRight = value;
                    planeChanged = true;
                }
            }
        }


        public MeshGeometry3D Mesh
        {
            get
            {
                if (planeChanged)
                {
                    mesh = new MeshGeometry3D();
                    double y0 = upperLeft.Y;
                    double y1 = y0 + lowerRight.Y - upperLeft.Y;
                    double x0 = upperLeft.X;
                    double x1 = x0 + lowerRight.X - upperLeft.X;
                    double z0 = upperLeft.Z;
                    double z1 = z0 + lowerRight.Z - upperLeft.Z;

                    mesh.Positions.Add(new Point3D(x0, y0, z0));
                    mesh.Positions.Add(new Point3D(x1, y0, z1));
                    mesh.Positions.Add(new Point3D(x0, y1, z0));
                    mesh.Positions.Add(new Point3D(x1, y1, z1));
                    Vector3D norm = Vector3D.CrossProduct(lowerRight - upperLeft, new Vector3D(0, 1, 0));

                    mesh.Normals.Add(norm);
                    mesh.Normals.Add(norm);
                    mesh.Normals.Add(norm);
                    mesh.Normals.Add(norm);
                    mesh.TextureCoordinates.Add(new Point(0, 1));
                    mesh.TextureCoordinates.Add(new Point(1, 1));
                    mesh.TextureCoordinates.Add(new Point(0, 0));
                    mesh.TextureCoordinates.Add(new Point(1, 0));
                    mesh.TriangleIndices.Add(0);
                    mesh.TriangleIndices.Add(1);
                    mesh.TriangleIndices.Add(2);
                    mesh.TriangleIndices.Add(3);
                    mesh.TriangleIndices.Add(2);
                    mesh.TriangleIndices.Add(1);
                    planeChanged = false;
                }

                return mesh;
            }
        }

        private Point3D upperLeft;
        private Point3D lowerRight;
        private MeshGeometry3D mesh;
        private bool planeChanged;
    }
}